//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Mapping Application Block
//===============================================================================

using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;

namespace EntLibContrib.Mapping.Configuration.Design
{
	/// <summary>
	/// This class builds the configuration data from the node hierarchy
	/// to save data from the console to configuration.
	/// </summary>
	public class MappingSettingsBuilder
	{
		#region Fields
		private MappingSettingsNode mappingSettingsNode;
		private MappingSettings mappingSettings;
		#endregion

		#region Construction
		/// <summary>
		/// Initializes a new instance of the <see cref="MappingSettingsBuilder"/> class.
		/// </summary>
		/// <param name="serviceProvider">The service provider.</param>
		/// <param name="mappingSettingsNode">The mapping settings node.</param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "serviceProvider")]
		public MappingSettingsBuilder(IServiceProvider serviceProvider, MappingSettingsNode mappingSettingsNode)
		{
			this.mappingSettingsNode = mappingSettingsNode;
			mappingSettings = new MappingSettings();
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Builds the configuration data for the mapping settings.
		/// </summary>
		/// <returns>A mapping settings instance</returns>
		public MappingSettings Build()
		{
			if (!mappingSettingsNode.RequirePermission)	// don't set if false
				mappingSettings.SectionInformation.RequirePermission = mappingSettingsNode.RequirePermission;

			BuildMappers();

			return mappingSettings;
		}
		#endregion

		#region Private Methods
		private void BuildMappers()
		{
			foreach (MapperBaseNode mapperNode in mappingSettingsNode.Nodes)
			{
				mappingSettings.Mappers.Add(BuildMaps(mapperNode));
			}
		}

		private static MapperBaseData BuildMaps(MapperBaseNode mapperNode)
		{
			MapperBaseData mapperData = mapperNode.MapperData;
			MapperNode node = mapperNode as MapperNode;
			if (node != null)
			{
				foreach (MapBaseNode mapNode in mapperNode.Nodes)
				{
					((MapperData)mapperData).Maps.Add(mapNode.MapData);
				}
			}

			return mapperData;
		}
		#endregion
	}
}